using System;
using System.Data;
using System.Reflection;

namespace Serpis
{


	public class Persister
	{
		public void Save(object model) //Mirar en el tipo y ver si tiene definido el FieldAttribute, o si tiene definido el PrimaryKey
		{
//			IDbCommand dbCommand = AppDbConnection.Instance.DbConnection.CreateCommand();
//			
//			if(articulo.Id == 0) //insert
//				dbCommand.CommandText = insertCommand;
//			else { //update
//				dbCommand.CommandText = updateCommand;
//				addParameter(dbCommand, "id", articulo.Id);
//			}
//			
//			addParameter(dbCommand, "nombre", articulo.Nombre);
//			addParameter(dbCommand, "precio", articulo.Precio);
//			addParameter(dbCommand, "categoria", articulo.Categoria);
//			
//			dbCommand.ExecuteNonQuery();
			
			PersisterInfo persisterInfo = new PersisterInfo(model.GetType());
			
			IDbCommand dbCommand = AppDbConnection.Instance.DbConnection.CreateCommand();
			
			object id = persisterInfo.PrimaryKey.GetValue(model, null);
			
			if (id == null || id.Equals("") || Convert.ToInt64(id) == 0) //insert
				dbCommand.CommandText = persisterInfo.insertCommand;
			else {
				dbCommand.CommandText = persisterInfo.updateCommand;
				addParameter(dbCommand, persisterInfo.PrimaryKeyName, id);
			}
			
			
			int index = 0;
			foreach (PropertyInfo propertyInfo in persisterInfo.Fields) {
				object value = propertyInfo.GetValue(model, null);
				addParameter(dbCommand, persisterInfo.FieldNames[index], value);
				index++;
			}
			
			dbCommand.ExecuteNonQuery();
		}
		
		private void addParameter(IDbCommand dbCommand, string parameterName, object parameterValue)
		{
			IDbDataParameter dbDataParameter = dbCommand.CreateParameter();
			dbDataParameter.ParameterName = parameterName;
			dbDataParameter.Value = parameterValue;
			dbCommand.Parameters.Add(dbDataParameter);
		}
		
		public object Load(Type type, object id)
		{
			return null;
		}
	}
}
